// server.go
package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"time"
)

func main() {
	listener, err := net.Listen("tcp", "127.0.0.1:9000")
	if err != nil {
		log.Fatalf("listen error: %v", err)
	}
	log.Println("Echo 服务器已启动，等待连接 ...")

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Printf("accept error: %v", err)
			continue
		}
		log.Printf("新连接：remote=%s local=%s", conn.RemoteAddr(), conn.LocalAddr())
		go handleConn(conn)
	}
}

func handleConn(conn net.Conn) {
	defer func() {
		log.Printf("关闭连接：remote=%s", conn.RemoteAddr())
		conn.Close()
	}()

	// 设置读写超时，避免客户端长时间不发数据造成阻塞
	if err := conn.SetDeadline(time.Now().Add(2 * time.Minute)); err != nil {
		log.Printf("set deadline error: %v", err)
		return
	}

	reader := bufio.NewScanner(conn) // 默认以换行符分割
	for reader.Scan() {
		line := reader.Text()
		log.Printf("收到：%q", line)
		if _, err := fmt.Fprintf(conn, "echo: %s\n", line); err != nil {
			log.Printf("write error: %v", err)
			return
		}
		// 每次成功读写后刷新超时
		conn.SetDeadline(time.Now().Add(2 * time.Minute))
	}

	if err := reader.Err(); err != nil {
		log.Printf("read error: %v", err)
	} else {
		log.Println("客户端主动断开，读取到 EOF")
	}
}
